<?php
namespace App\Http\Questionnaire\Controllers;

use Illuminate\Http\Request;
use App\Http\Admin\Controllers\Controller as Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Questionnaire\Controllers\PageController;
use App\Http\Questionnaire\Controllers\WordController;
use App\Http\Questionnaire\Controllers\ProblemQController;

class QuestionnaireController  extends Controller
{
    public function __construct(Request $request){
        $token = getToken($request);
        $uid =Redis::get("code:".$token);
        $this->uid=$uid;
    }




    /*
     *  返回请求页面基本数据
     *  @author 小林《1814992057@qq.com》
     *  @datetime   2019/11/18
     *  @request    get
     *  @return array
     *          questionnaireType array 问卷类型
     *          questionnaireStatus array 问卷是否禁止访问
     * */
    public function created(){
        if(if_authority($this->uid,"questionnaireDemo")){
            return [
                'status_code'      => 200,
                'message'     =>  '请求成功',
                'data' => [
                    "questionnaireType"=>[//问卷测试权限
                        "1"=>"协议书类"
                    ]
                ]
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '请求成功',
                'data' => create(['questionnaireType','questionnaireStatus'])
            ];
        }

    ;
}
    /*
     *  创建问卷
     *  @author 小林《1814992057@qq.com》
     *  @datetime   2019/11/18
     *  @request    post 
     *  @Param title        String  标题         title存在 格式为非空白字符 长度大于2小于20
     *  @Param type         Int     问卷类型      type存在  格式为字数字 长度等于1
     *  @Param description  String  备注         description格式为非空白字符 长度小于100
     *  @Param purpose      String  用途         purpose存在 格式为非空白字符 长度小于100
     *  @Param status       Int     是否禁止访问  status存在 格式为字数字 长度等于1
     * */
    public function add(Request $request){
        //title错误 32001 type错误 32002 description错误 32003 purpose错误 32004 status错误 32005
        $data=$request->only("title","type","description","purpose","status");

        //验证
        
        //title不存在 格式为空白字符 长度少于2大与20
        if(!array_key_exists('title',$data)||!preg_match('/^[\S]{2,20}$/u',$data['title'])) return ThrowApiExc('32001');
        //type不存在 格式为非字数字 长度不等于1
        if(!array_key_exists('type',$data)||!preg_match('/^[\d]{1,200}$/u',$data['type'])) return ThrowApiExc('32002');
        //description不存在 格式为空白字符 长度大于100
        if(!array_key_exists('description',$data)||!preg_match('/^[\S]{0,100}$/u',$data['description'])) return ThrowApiExc('32003');
        //purpose不存在 格式为空白字符 长度大于100
        if(!array_key_exists('purpose',$data)||!preg_match('/^[\S]{0,100}$/u',$data['purpose'])) return ThrowApiExc('32004');
        //status不存在 格式为非字数字 长度不等于
        if(!array_key_exists('status',$data)||!preg_match('/^[\d]{1}$/u',$data['status'])) return ThrowApiExc('32005');

        $data['createdTime']=date("Y-m-d H:i:s",time());
        $data['updateTime']=date("Y-m-d H:i:s",time()); 
        $data['createdUid']=$this->uid;
        $data['updateUid']=$this->uid;

        $res = DB::table("q_questionnaire")->insertGetId($data);

        if($res){

            $wid = DB::table("q_word")->insertGetId(["fWordId"=>0,"title"=>$data['title']]);

            DB::table("q_questionnaire")->where("id",$res)->update(["wid"=>$wid]);

            return [
                'status_code'      => 200,
                'message'     =>  '提交成功',
                'data' => $res
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '提交失败 联系后端开发',
                'data' => $res
            ];
        }

    }

    /*
     *  修改问卷
     *  @author 小林《1814992057@qq.com》
     *  @datetime   2019/11/18
     *  @request    put
     *  @Param title        String  标题         title存在 格式为非空白字符 长度大于2小于20
     *  @Param type         Int     问卷类型      type存在  格式为字数字 长度等于1
     *  @Param description  String  备注         description格式为非空白字符 长度小于100
     *  @Param purpose      String  用途         purpose存在 格式为非空白字符 长度小于100
     *  @Param status       Int     是否禁止访问  status存在 格式为字数字 长度等于1
     * */
    public function update(Request $request,$qid){

        //title错误 32001 type错误 32002 description错误 32003 purpose错误 32004 status错误 32005
        $data=$request->only("title","type","description","purpose","status","Ofqp");
 
        //验证

        //title不存在 格式为空白字符 长度少于2大与20
        if(array_key_exists('title',$data)&&!preg_match('/^[\S]{2,20}$/u',$data['title'])) return ThrowApiExc('32001');
        //type不存在 格式为非字数字 长度不等于1
        // if(array_key_exists('type',$data)&&!preg_match('/^[\d]{200}$/u',$data['type'])) return ThrowApiExc('32002');
        if(array_key_exists('type',$data)&&!preg_match('/^[\d]{1,200}$/u',$data['type'])) return ThrowApiExc('32002');
        //description不存在 格式为空白字符 长度大于100
        if(array_key_exists('description',$data)&&!preg_match('/^[\S]{0,100}$/u',$data['description'])) return ThrowApiExc('32003');
        //purpose不存在 格式为空白字符 长度大于100
        if(array_key_exists('purpose',$data)&&!preg_match('/^[\S]{0,100}$/u',$data['purpose'])) return ThrowApiExc('32004');
        //status不存在 格式为非字数字 长度不等于1
        if(array_key_exists('status',$data)&&!preg_match('/^[\d]{1}$/u',$data['status'])) return ThrowApiExc('32005');

        $data['updateTime']=date("Y-m-d H:i:s",time());
        $data['updateUid']=$this->uid;
        $res = DB::table("q_questionnaire")->where("id",$qid)->update($data);

        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '提交成功',
                'data' => $res
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '未修改数据 与原有值一致',
                'data' => $res
            ];
        }

    }

    /*
     *  查询问卷
     *  @author 小林《1814992057@qq.com》
     *  @datetime   2019/11/18
     *  @request    get
     *  @return 问卷id 标题 类型 创建时间 修改时间 备注 用途 状态 创建人 修改人
     * */

    public function select(Request $request){

        //搜索条件
        $data = $request->only("type");
        if(array_key_exists('type',$data)&&!preg_match('/^[\S]{1,20}$/u',$data['type'])) return ThrowApiExc('32002');
        if(array_key_exists('type',$data)){
            $res = DB::table("q_questionnaire as q_q")
                ->select("q_q.*","u.name as createdUid","u2.name as updateUid")
                ->leftJoin("users as u","u.id","=","q_q.createdUid")
                ->leftJoin("users as u2","u2.id","=","q_q.updateUid")
                ->where([
                    ["q_q.type",$data['type']],
                    ['q_q.status',1]
                ])
                ->get();
        }else{
            $res = DB::table("q_questionnaire as q_q")
                ->select("q_q.*","u.name as createdUid","u2.name as updateUid")
                ->leftJoin("users as u","u.id","=","q_q.createdUid")
                ->leftJoin("users as u2","u2.id","=","q_q.updateUid")
                ->where([
                    ['q_q.status',1],
                ])
                ->get();
        }

        if(if_authority($this->uid,"questionnaireDemo")){
            $qidArr = create(['questionnaireDemoIds']);
            foreach($res as $k=>$v){
                if(!in_array($v['id'],$qidArr['questionnaireDemoIdsw'])){
                    unset($res[$k]);
                }
            }
        }

        return [
            'status_code'      => 200,
            'message'     =>  '请求成功',
            'data' => $res
        ];
    }


    /*
     *  删除问卷
     *  @author 小林《1814992057@qq.com》
     *  @datetime   2019/11/18
     *  @request    delete
     *  @return     array
     * */

    public function delete($qid){

        $res = DB::table("q_questionnaire")->where("id",$qid)->update([
            'status'=>0
        ]);
        return [
            'status_code'      => 200,
            'message'     =>  '删除成功',
            'data' => $res
        ];
    }


    /*
    *  复制问卷
    *  @author 小林《1814992057@qq.com》
    *  @datetime   2019/11/18
    *  @request    post
    *  @return     array
    * */
    public function copy_questionnaire(Request $request,$qid){

        $questionnaire=DB::table("q_questionnaire")->where([
            ['id',"=",$qid]
        ])->get()->toArray();

        foreach($questionnaire as $k=>$v){
            //创建wid

            $wordData = DB::table("q_word")->where("id",$v['wid'])->first();
            unset($wordData['id']);
            $wordId = DB::table("q_word")->insertGetId($wordData);
            //创建问卷
            $questionnaireData=$v;
            unset($questionnaireData['id']);
            $questionnaireData['wid']=$wordId;
            $questionnaireId = DB::table("q_questionnaire")->insertGetId($questionnaireData);
            $qpids = $this->cp_qqp($v['id'],$questionnaireId,0,0);

            
            $qofp=DB::table("q_relation")->whereIn("qpid",array_keys($qpids))->get()->toArray();
            // var_dump($qpids);
            // $qpidStr=implode(",",array_keys($qpids));
            // $qofp=DB::table("q_relation")->whereRaw("qpid,in(?)",[$qpidStr])->get()->toArray();
            $relationIdData=DB::table("q_relation")->whereIn("relationId",array_keys($qpids))->get()->toArray();
            foreach($qofp as $kk=>$vv){
                if($vv['qpid']) $qofp[$kk]['qpid']=$qpids[$vv['qpid']];
                if($vv['relationId']) $qofp[$kk]['relationId']=$qpids[$vv['relationId']];
                unset($qofp[$kk]['id']);
            } 
            $wordIds = $this->cp_word($wordId,$v['wid'],$qpids);
            $uploadWords = DB::table('q_word_json')->whereIn('wid',$wordIds)->get()->toArray();
            foreach($uploadWords as $kk=>$vv){

                foreach($qpids as $kkk=>$vvv){
                    $uploadWords[$kk]['json']=str_replace("{{2,".$kkk,"{{2,".$vvv,$uploadWords[$kk]['json']);
                }

                foreach($wordIds as $kkk=>$vvv){
                    $uploadWords[$kk]['json']=str_replace("{{3,".$kkk,"{{3,".$vvv,$uploadWords[$kk]['json']);     
                }

                DB::table('q_word_json')->where('id',$vv['id'])->update(['json'=>$uploadWords[$kk]['json']]);

            }
            DB::table("q_relation")->insert($qofp);
            // DB::table("q_relation")->insert($relationIdData);
            
        }

        return [
            'status_code'      => 200,
            'message'     =>  '复制成功',
            'data' => 1
            ];
    }


    public function cp_qqp($oldQid,$newQid,$fid,$newfid){
        $newids=[];
        $data = DB::table("q_q_p")->where([
            ['questionnaireId',$oldQid],
            ['fqaspId',$fid]
        ])->get()->toArray();
        foreach($data as $k=>$v){
            $qpData=$v;
            unset($qpData['id']);
            $qpData['fqaspId']=$newfid;
            $qpData['questionnaireId']=$newQid;
            $qpData['oldId']=$v['id'];
            $newfid2=DB::table("q_q_p")->insertGetId($qpData);
            $newids[$v['id']]=$newfid2;

            $newids3=$this->cp_qqp($oldQid,$newQid,$v['id'],$newfid2);
            $newids=$newids+$newids3;

        }
        return $newids;
    }

    public function cp_word($newWordId,$oldWordId,$qpids){
        $newids=[];
        $data = DB::table("q_word")->where("fWordId",$oldWordId)->get()->toArray();
        foreach($data as $k=>$v){
            $oldData = $v;
            $oldData['fWordId']=$newWordId;
            $oldData['oldId']=$v['id'];
            unset($oldData['id']);
            foreach($qpids as $kk=>$vv){
                $oldData['where']=str_replace($kk,$vv,$oldData['where']);
            }
            
            $wordId = DB::table("q_word")->insertGetId($oldData);
            $json_word = DB::table("q_word_json")->where("wid",$v['id'])->get()->toArray();
            foreach($json_word as $kk=>$vv){
                $word_json_data=$vv;
                unset($word_json_data['id']);
                $word_json_data['wid']=$wordId;
                DB::table("q_word_json")->insertGetId($word_json_data);
            }
            $newids[$v['id']]=$wordId;
            $newids3=$this->cp_word($wordId,$v['id'],$qpids);
            $newids=$newids+$newids3;
        }
        return $newids;
    }

    public function linshidemo(){
        $questionnaireData=DB::table("q_questionnaire")->where([
            ['id',">",29],
            ['id','<',60]
        ])->get()->toArray();

        foreach($questionnaireData as $k=>$v){
            DB::table("q_word")->where("id",$v['wid'])->update(['qid'=>$v['id']]);
            $wids=$this->recursion($v['wid']);
            DB::table("q_word")->whereIn("id",$wids)->update(['qid'=>$v['id']]);
        }

    }

    public function recursion($wid){
        $wordData=DB::table("q_word")->where("fWordId",$wid)->get()->toArray();
        $wids = array_column($wordData,'id');
        foreach($wordData as $k=>$v){
            $wids2 = $this->recursion($v['id']);
            $wids = array_merge($wids,$wids2);
        }

        return $wids;

    }

    
}
